package com.djsearch.ui;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.json.JSONException;

import android.content.Context;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;

import com.djsearch.R;
import com.djsearch.adapter.MyCollectListViewAdapter;
import com.djsearch.bean.GoodsBaseBean;
import com.djsearch.bean.GroupBuyGoods;
import com.djsearch.bean.MyCollect;
import com.djsearch.controller.AsyncHandler;
import com.djsearch.controller.IRequest;
import com.djsearch.controller.IResponse;
import com.djsearch.controller.JSONReq;
import com.djsearch.controller.JSONResp;
import com.djsearch.ui.GroupShopActivity.RequestParamStruct;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
/**
 * 我的收藏
 * @author chenyang2
 *
 */
public class MyCollectActivity extends BaseActivity{

	private Context mContext;
	private List<MyCollect> goodsList;
	private List<MyCollect> nextPagegoodsList;//存放下一页请求的新数据
	private ListView collectListView;
	private MyCollectListViewAdapter collectListViewAdapter;
	private Button btnBack;
	private int PAGE = 1;
	final private int pageNum = 10;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().requestFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.mycollect_layout);
		mContext = this;
		goodsList = new ArrayList<MyCollect>();//当前页面数据
		nextPagegoodsList = new ArrayList<MyCollect>(); //更多（下一页数据）
		collectListViewAdapter = new MyCollectListViewAdapter(mContext, goodsList);
		//初始化主界面
		initView();
		//初始化主界面相关点击事件
		initOnClick();
		//
		initHandler();
	}
	
	
	@Override
	void initHandler() {
		// TODO Auto-generated method stub
		
	}

	@Override
	void initView() {
		// TODO Auto-generated method stub
		collectListView = (ListView)findViewById(R.id.collectListView);
		collectListView.setAdapter(collectListViewAdapter);
		btnBack = (Button)findViewById(R.id.btnBack);
		requestCollectData();
		
	}

	@Override
	void initOnClick() {
		
		btnBack.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		
		collectListView.setOnScrollListener(new AbsListView.OnScrollListener() {
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
				if ( scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
					if (view.getLastVisiblePosition() == (view.getCount() - 1)) {
						if (10 <= goodsList.size()  ) {
							requestCollectData();
						}
					}
				}
			}
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
				
			}
		});
		
		collectListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				startActivity(mContext, MyCollectDetailsActivity.class, 0, 
						goodsList.get(position));
			}
		});
		
	}

	
	
	
	/**
	 * 请求服务器数据方法
	 * {“userId”,”page”:”1”,”pageNum”:”10”}
	 */
	private void requestCollectData() {
		IRequest request = new JSONReq("mycollect");
		request.putParam("userId", preferences.getString("userId", ""));
		request.putParam("page", PAGE);
		request.putParam("pageNum", pageNum);
		HTTP.post(request, new AsyncHandler(){
			@Override
			public void onStart() {
				showDialog("正在加载...");
			}
			/**
			 * {"description":"仅售19.9元！最高价值60元的17.5影院电影票1张，2D\/3D可兑。",
			 * "userId":"13dfc3db636","name":"17.5影院电影单人票",
			 * "shopUrl":"http:\/\/m.meituan.com\/zhengzhou\/deal\/6046645.html",
			 * "smallImage":"http:\/\/p0.meituan.net\/275.168\/deal\/__6934150__2268597.jpg",
			 * "place":"二七区大学路80号长城康桥华城11号楼4层",
			 * "bigImage":"http:\/\/p0.meituan.net\/275.168\/deal\/__6934150__2268597.jpg",
			 * "telephone":"0371-86106962\/86106960,0371-60106677"}
			 * 
			 * 
			 * 
			 * {"description":"【品牌特卖】真我永恒 针织衫女韩版 包邮新款潮长袖套头Q1383102","userId":"13dfc3db636",
			 * "name":"【品牌特卖】真我永恒 针织衫女韩版 包邮新款潮长袖套头Q1383102",
			 * "shopUrl":"http:\/\/item.tbsandbox.com\/item.htm?id=1500010955454",
			 * "smallImage":"http:\/\/img03.taobaocdn.com\/bao\/uploaded\/i3\/T1XnvDXexnXXamAlk3_050741.jpg_b.jpg",
			 * "place":"",
			 * "bigImage":"http:\/\/img03.taobaocdn.com\/bao\/uploaded\/i3\/T1XnvDXexnXXamAlk3_050741.jpg_b.jpg","telephone":""}
			 */
			@Override
			public void onSuccess(JSONResp response) {
				// TODO Auto-generated method stub
				int result = response.result();
				if(IResponse.Success==result){
					    ++PAGE;
						getDataToResolve(response);
				} else if (IResponse.Fail==result) {
					//返回数据失败
					getDataToResolve(response);
					Toast.makeText(mContext, "没有数据", 5000).show();
				}
					missDialog();
			}
			@Override
			public void onFailure(Throwable e, String response) {
				// TODO Auto-generated method stub
				missDialog();
				Toast.makeText(mContext, "网络传输错误", 5000).show();
			}
			
		});
	}
	
	
	@Override
	void getDataToResolve(JSONResp response) {
		// TODO Auto-generated method stub

		try {
			Gson gson = new Gson();   
	        Type type = new TypeToken<List<MyCollect>>(){}.getType();  //指定集合对象属性  
	        List<MyCollect> fromJson = gson.fromJson(response.getString("returnMessage"), type); 
	        nextPagegoodsList.addAll(fromJson);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (nextPagegoodsList.size() == 0) {
				//当没有更多的数据了处理
				Toast.makeText(mContext, "暂无数据", 5000).show();
			} else {
				goodsList.addAll(nextPagegoodsList);
				nextPagegoodsList.clear();
			}
			collectListViewAdapter.refreshData(goodsList);
		}
	}
	
	
	/**
	 * 点击返回键
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			startActivity(mContext, SetActivity.class, 1);
		}
		return false;
	}

}
